package Graphique;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.security.auth.login.LoginException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import Serveur.Utilisateur;

import Client.Client;

public class Inscription extends JFrame{
	private static final long serialVersionUID = 1L;

	private Client client;

	private JLabel intro = new JLabel("Inscris-toi : ");
	private JLabel labelNom = new JLabel("Nom :");
	private JLabel labelPrenom = new JLabel("Prenom :");
	private JLabel labelLogin = new JLabel("Login :");
	private JLabel labelMdp = new JLabel("Mot de passe :");
	private JTextField champsNom = new JTextField();
	private JTextField champsPrenom = new JTextField();
	private JTextField champsLogin = new JTextField();
	private JPasswordField champsMdp = new JPasswordField();
	private JButton validation = new JButton("Valider");
	private JButton annuler = new JButton("Annuler"); 
	private ActionListenerValidation alc = new ActionListenerValidation();
	
	public Inscription(Client client){
		super("Inscription");
		
		this.setSize(250, 250);
		
		validation.addActionListener(alc);
		annuler.addActionListener(alc);
		
		JPanel jp = new JPanel();
		jp.setLayout(new GridLayout(4, 2));
		jp.add(labelNom);
		jp.add(champsNom);
		jp.add(labelPrenom);
		jp.add(champsPrenom);
		jp.add(labelLogin);
		jp.add(champsLogin);
		jp.add(labelMdp);
		jp.add(champsMdp);
		
		JPanel jp2 = new JPanel();
		jp2.setLayout(new GridLayout(2,1));
		jp2.add(validation);
		jp2.add(annuler);
		
		this.add(intro, BorderLayout.NORTH);
		this.add(jp, BorderLayout.CENTER);
		this.add(jp2, BorderLayout.SOUTH);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		this.pack();
		this.client = client;
	}
	
	private class ActionListenerValidation implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			Object obj = e.getSource();
			
			if(validation.equals(obj)){
				Utilisateur u = new Utilisateur(champsPrenom.getText(), champsNom.getText(), champsLogin.getText(), champsMdp.getText());
				
				try {
					client.incription(u);
					client.connexion(champsLogin.getText(), champsMdp.getText());
					new Connecte(client);
					dispose();
				} catch (RemoteException e1) {
					e1.printStackTrace();
				} catch (LoginException e1) {
					e1.printStackTrace();
				}
			}
			if(annuler.equals(obj)){
				dispose();
			}
			
		}
	}
}
